package com.hwadee.ems.service.impl;

import java.util.Map;
import java.util.HashMap;
import java.util.concurrent.TimeUnit;

import jakarta.annotation.Resource;
import jakarta.annotation.PostConstruct;
import jakarta.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Service;
import org.springframework.data.redis.core.StringRedisTemplate;

import cn.hutool.core.lang.UUID;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.hwadee.ems.domain.po.User;
import com.hwadee.ems.mapper.UserMapper;
import com.hwadee.ems.service.IUserService;
import com.hwadee.ems.service.IClassService;
import com.hwadee.ems.service.IDepartmentService;
import com.hwadee.ems.domain.po.Class;
import com.hwadee.ems.domain.po.Department;
import com.hwadee.ems.domain.dto.Result;
import com.hwadee.ems.domain.dto.UserDTO;
import com.hwadee.ems.domain.dto.LoginFormDTO;
import static com.hwadee.ems.constant.RedisConstants.*;

/**
 * <p>
 * 用户 服务实现类
 * </p>
 *
 * @author EnosElinsa
 * @since 2024/06/21
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {
    
    private static IUserService instance;

    public static IUserService getInstance() {
        return instance;
    }

    @PostConstruct
    void init() {
        instance = this;
    }

    @Resource
    private StringRedisTemplate srt;

    @Resource
    private IClassService classService;

    @Resource
    private IDepartmentService departmentService;

    @Override
    public Result<UserDTO> login(LoginFormDTO loginForm) {
        // 根据学号或工号查询用户
        User user = lambdaQuery().eq(User::getNumber, loginForm.getNumber()).one();
        
        // 判断用户是否存在
        if (user == null) {
            // 不存在，返回错误信息
            return Result.error("学号/工号或者密码错误");
        }

        // 验证密码
        if (!loginForm.getPassword().equals(user.getPassword())) {
            // 密码错误，返回错误信息
            return Result.error("学号/工号或者密码错误");
        }

        // 验证成功，保存用户信息到 redis 中
        // 随机生成 Token，作为登录令牌
        String token = UUID.randomUUID().toString(true);
        // 将 User 对象转成为 HashMap 存储 
        UserDTO userDTO = BeanUtil.copyProperties(user, UserDTO.class);
        userDTO.setToken(token);
        Class classEntity = classService.getById(user.getClassId());
        if (classEntity != null) {
            userDTO.setClassName(classEntity.getName());
        }
        Department department = departmentService.getById(user.getDepartmentId());
        if (department != null) {
            userDTO.setDepartmentName(department.getName());
        }
        Map<String, Object> userMap = BeanUtil.beanToMap(userDTO, new HashMap<>(),
            CopyOptions.create()
                .setIgnoreNullValue(true)
                .setFieldValueEditor((fieldName, fieldValue) -> fieldValue == null ? "" : fieldValue.toString())
        );
        String key = LOGIN_USER_KEY + token;
        srt.opsForHash().putAll(key, userMap);
        // 设置 Token 过期时间
        srt.expire(key, LOGIN_USER_TTL, TimeUnit.MINUTES);

        // 返回 Token 
        return Result.ok(userDTO);
    }

    @Override
    public Result<Void> logout(HttpServletRequest request) {
        String token = request.getHeader("token");
        srt.delete(LOGIN_USER_KEY + token);

        return Result.ok();
    }

}
